global._ = require('lodash')
global.APP_PATH = process.cwd()
global.path = require('path')
global.fs = require('fs')
global.configure = require('little-man-config')
global.pager = require('../../framework/lib/pager')
global.log4js = require('../../framework/lib/log4js')
global.helper = require('../../framework/lib/helper')
global.moment = require('moment')

const apiFree = require('api-free')                             // 载入api-free 核心组件

global.M = apiFree.M
global.DB = apiFree.DB
global.dbUtil = apiFree.dbUtil

// 载入app配置文件
const kong_cfg = configure.get('kong')
const service_config = kong_cfg.services;
const api_version_key = kong_cfg.api_version_key || 0;

const upstreamService = require('../../service/common/kong/upstream')
const serviceService = require('../../service/common/kong/service')
const routeService = require('../../service/common/kong/route')
const pluginService = require('../../service/common/kong/plugin')

// 遍历sys_app表，向kong 同步消费者
async function scan (args = {}) {
    let services = service_config
    // 查找消费者
    for (let i = 0; i < services.length; i++) {
        let item = services[i]

        await _scanItem({...item})
    }

    return true
}

async function _scanItem (item = {}) {
    // 获取服务详情
    let _service_detail = await serviceService.get(api_version_key ? `${api_version_key}.${item.name}` : item.name);
    if(!_service_detail.id) return false;

    let _plugins = await pluginService.list(_service_detail.id)
    let _routes = await routeService.list_service_route(_service_detail.id)
    let _upstream = await upstreamService.get(_service_detail.host)

    // 删除 服务插件插件
    _plugins = _plugins.data || [];
    for(let pi=0;pi<_plugins.length;pi++) {
        let _ret = await pluginService.delete(_plugins[pi].id);
        log4js.debug('删除 服务插件插件 ',_plugins[pi].name, _ret)
    }

    // 删除 服务路由
    _routes = _routes.data || [];
    for(let ri=0;ri<_routes.length;ri++) {
        let _ret = await routeService.delete(_routes[ri].id);
        log4js.debug('删除 服务路由 ',_routes[ri].name, _ret)
    }

    // 删除 服务
    let _ret = await serviceService.delete(_service_detail.id)
    log4js.debug('删除 服务 ',_service_detail.name, _ret)

    // 删除 upstream
   !!_upstream.id && (_ret = await upstreamService.delete(_upstream.id))
    log4js.debug('删除 upstream ',_upstream.name, _ret)
}

// 初始化 api-free
apiFree.init(configure.get('apifree')).then(async ()=>{
    await scan()
    log4js.debug('DONE')
    process.exit(0)
}).catch(err => {
    log4js.error(err)
})


